﻿using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Configuration;

namespace MagicTraderLib
{
    public static class WebHelper
    {
        public static string DownloadString(string url)
        {
            if (String.IsNullOrWhiteSpace(url)) 
                throw new ArgumentNullException("url");

            using (var client = new WebClient())
            {
                client.Headers.Add("user-agent", "Only a test!"); // ivm 403 errors
                return client.DownloadString(url);
            }
        }

        public static void DownloadFile(string pageUrl, string fileName)
        {
            var pageContent = DownloadString(pageUrl);
            var fileInfo = new FileInfo(fileName);

            SavePagina(pageContent, fileInfo);
        }

        public static int LeesNedermagicAantalPaginas(string url)
        {
            if (String.IsNullOrWhiteSpace(url))
                throw new ArgumentNullException("url");

            using (var client = new WebClient())
            {
                client.Headers.Add("user-agent", "Only a test!"); // ivm 403 errors

                using (Stream stream = client.OpenRead(url))
                {
                    var reader = new StreamReader(stream);
                    while (true)
                    {
                        // TODO : generieke Functie met een callback?
                        var line = reader.ReadLine();
                        if (line == null)
                            return 0;

                        if (!line.Contains("pagina 1 van de "))
                            continue;

                        line = line.Trim().Replace("pagina 1 van de ", String.Empty);
                        int nr;
                        if (int.TryParse(line, out nr))
                        {
                            return nr;
                        }
                        return 0;
                    }
                }
            }
        }

        private static void SavePagina(string content, FileInfo file)
        {
            if (file == null)
                throw new ArgumentNullException("file");

            if (string.IsNullOrWhiteSpace(content))
                throw new ArgumentNullException("content");

            SavePaginaInternal(content, file);
        }

        private static void SavePaginaInternal(string content, FileInfo file)
        {
            if (!Directory.Exists(file.DirectoryName))
            {
                Directory.CreateDirectory(file.DirectoryName);
            }

            using (var writer = new StreamWriter(file.FullName))
            {
                writer.Write(content);
            }
        }
    }
}
